import { MySprite } from "../effect/MySprite";
import { ClickHandler } from "../../utils/clickHandler";
import { EventBus } from "../../utils/EventBus";
import gsap from "gsap";

// 汽车类
export class Car {
  constructor(model, scene, camera, controls) {
    this.model = model;
    this.scene = scene;
    this.camera = camera;
    this.controls = controls;

    // 模型对象
    this.carModel = {
      body: {
        main: {
          //车身
          name: "Object_103",
          model: {}, // 小物体对象
        },
        roof: {
          //车顶
          name: "Object_110",
          model: {},
        },
        leftDoor: {
          //左车门
          name: "Object_64",
          model: {},
          mark: [
            {
              name: "sprite",
              url: "image/sprite.png",
              scale: [0.2, 0.2],
              position: [1.07, 1.94, -0.23], // 参考车门的原点进行位移
            },
          ],
        },
        rightDoor: {
          //右车门
          name: "Object_77",
          model: {},
          mark: [
            {
              name: "sprite",
              url: "image/sprite.png",
              scale: [0.2, 0.2],
              position: [-1, 0.5, 0.78, -0.23],
            },
          ],
        },
      },
    };

    this.info = {
      // 车身颜色
      color: [
        {
          name: "土豪金",
          color: "#ff9900",
          isSelected: true,
        },
        {
          name: "传奇黑",
          color: "#343a40",
          isSelected: false,
        },
        {
          name: "海蓝",
          color: "#409EFF",
          isSelected: false,
        },
        {
          name: "玫瑰紫",
          color: "#6600ff",
          isSelected: false,
        },
        {
          name: "银灰色",
          color: "#eee",
          isSelected: false,
        },
      ],
      // 贴膜
      film: [
        {
          name: "高光",
          price: 0,
          isSelected: true,
        },
        {
          name: "高光",
          price: 20000,
          isSelected: false,
        },
      ],
      // 默认总价
      allPrice: 2444700,
    };

    // 汽车各种视角坐标对象
    this.positionObj = {
      // 主驾驶
      main: {
        camera: {
          x: 0.36,
          y: 0.96,
          z: -0.16,
        },
        controls: {
          x: 0.36,
          y: 0.87,
          z: 0.03,
        },
      },
      // 副驾驶位
      copilot: {
        camera: {
          x: -0.39,
          y: 0.87,
          z: 0.07,
        },
        controls: {
          x: -0.39,
          y: 0.85,
          z: 0.13,
        },
      },
      // 外面观察
      copilot: {
        camera: {
          x: 3,
          y: 1.5,
          z: 3,
        },
        controls: {
          x: 0,
          y: 0,
          z: 0,
        },
      },
    };

    this.init();
    this.modifyCarBody();
  }

  // 初始化汽车
  init() {
    this.scene.add(this.model);

    // 通过数据结构名字，将小物体对象保存在数据结构中
    Object.values(this.carModel.body).forEach((obj) => {
      // 通过名字找到小物体
      obj.model = this.model.getObjectByName(obj.name);
    });

    // 订阅汽车修改颜色的事件和函数体
    EventBus.getInstance().on("changeCarColor", (colorStr) => {
      Object.values(this.carModel.body).forEach((obj) => {
        obj.model.material.color = new THREE.Color(colorStr);
      });

      // 保存用户选择的车颜色
      this.info.color.forEach((obj) => {
        obj.isSelected = false;
        if (obj.color === colorStr) {
          obj.isSelected = true;
        }
      });
    });

    // 订阅汽车贴膜修改的事件和函数体
    EventBus.getInstance().on("changeCarCoat", (coatName) => {
      if (coatName === "高光") {
        Object.values(this.carModel.body).forEach((obj) => {
          obj.model.material.roughness = 0.5;
          obj.model.material.metalness = 1;
          obj.model.material.clearcoat = 1;
        });
      } else if (coatName === "磨砂") {
        Object.values(this.carModel.body).forEach((obj) => {
          obj.model.material.roughness = 1;
          obj.model.material.metalness = 0.5;
          obj.model.material.clearcoat = 0;
        });
      }

      // 保存用户选择的贴膜类型
      Object.values(this.info.film).forEach((obj) => {
        obj.isSelected = false;
        if (obj.name === coatName) obj.isSelected = true;
      });
    });

    // 订阅计算总价事件
    EventBus.getInstance().on("celPrice", () => {
      // 获取isSelected为true的贴膜对象
      const filmTarget = this.info.film.find((obj) => obj.isSelected);

      // 动态总价
      const celPrice = this.info.allPrice + filmTarget.price;
      document.querySelector(".price>span").innerHTML = `￥${celPrice.toFixed(
        2
      )}`;
    });

    // 订阅视角切换事件
    EventBus.getInstance().on("changeCarAngleView", (viewName) => {
      this.setCameraAnimation(this.positionObj[viewName]);
    });
  }

  // 修改车身
  modifyCarBody() {
    // MeshPhysicalMaterial:物理材质
    const bodyMaterial = new THREE.MeshPhysicalMaterial({
      color: 0xff9900,
      roughness: 0.5, // 粗糙度
      metalness: 1, // 金属度
      clearcoat: 1, // 清晰度
      clearcoatRoughness: 0,
    });
    // 赋予给每个小物体
    Object.values(this.carModel.body).forEach((obj) => {
      obj.model.material = bodyMaterial;
    });
  }

  // 创建车门上的精灵物体
  createDoorSprite() {
    // 自定义合成数组
    const markList = [
      this.carModel.body.leftDoor,
      this.carModel.body.rightDoor,
    ];
    // 遍历创建精灵物体
    markList.forEach((obj) => {
      obj.mark.forEach((smallObj) => {
        if (smallObj.name === "sprite") {
          const sprite = new MySprite(smallObj);
          obj.model.add(sprite); // 将精灵物体添加到车门上

          // 为精灵物体进行射线交互的绑定
          ClickHandler.getInstance().addMesh(sprite, (clickThreeObj) => {
            // clickThreeobi: 标记点
            // clickThree0bj.parent: 0bject_77 车门物体(坐标轴原点在世界坐标系中心，旋转车门有问题)
            //clickThree0bj.parent.parent.parent (才是整个车门的最人物体对象，坐标系在车门框点固定住-旋转)
            const targetDoor = clickThreeObj.parent;
            // 判断是否开门
            if (!targetDoor.userData.isOpen) {
              // 绕x轴旋转60°开门
              this.setDoorAnimation(targetDoor, { x: Math.PI / 3 });
              targetDoor.userData.isOpen = true;
            } else {
              // 关门
              this.setDoorAnimation(targetDoor, { x: 0 });
              targetDoor.userData.isOpen = false;
            }
          });
        }
      });
    });
  }

  // 开关门动画
  setDoorAnimation(mesh, obj) {
    gsap.to(mesh.rotation, {
      x: obj.x,
      duration: 1,
      ease: "power1.in",
    });
  }

  // 摄像机和轨道控制器动画
  setCameraAnimation(dataObj) {
    gsap.to(this.camera.position, {
      ...dataObj.camera,
      duration: 1,
      ease: "power1.in",
    });
    gsap.to(this.controls.target, {
      ...dataObj.controls,
      duration: 1,
      ease: "power1.in",
    });
  }
}
